<?php

namespace App\Commands;

use App\Commands\Command;
use Illuminate\Contracts\Bus\SelfHandling;
use App\Models\ImportArea;
use App\Models\Area;
use App\Models\CompanyAddress;

class CompanyArea extends Command implements SelfHandling
{
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the command.
     *
     * @return void
     */
    public function handle()
    {
        $areas = ImportArea::all();
        $temp_area_ids = [];
        foreach ($areas as $value) {
            $province_id = Area::where('title', '=', trim($value->province))->pluck('area_id');
            $city_id = Area::where('title', '=',  trim($value->city) )->where('pid','=',$province_id)->pluck('area_id');
            $area_id = Area::where('title', '=',  trim($value->area) )->where('pid', '=', $city_id)->pluck('area_id');
        
            $company = CompanyAddress::where('company_id','=',$value->company_id)->first();
            if(empty($company))
            {
                $insert_row = array(
                    'company_id'        => $value->company_id,
                    'province'          => $province_id,
                    'city'              => $city_id,
                    'area'              => $area_id?:0,
                    'address'           => $value->address
                );
                CompanyAddress::firstOrCreate($insert_row);
            }
            else 
            {
                $company->province = $province_id;
                $company->city = $city_id;
                $company->area = $area_id;
                $company->address = $value->address;
                $company->save();
            }
            $temp_area_ids[] = $value->id;
        }
        // 更新organization表里记录后
        ImportArea::whereIn('id', $temp_area_ids)->delete();
    }
}
